<?php
/**
 * Created by PhpStorm.
 * User: eric
 * Date: 12/9/14
 * Time: 16:46
 */

namespace app\modules\fileuploads\controllers;
use app\modules\fileuploads\models\Uploads;
use yii\web\Controller;
use yii\web\UploadedFile;

class UploadController extends Controller{

    public function actionIndex($sign = false){
        if($sign !== false){
            $upload = Uploads::findOne($sign);
            if(is_null($upload))
                return json_encode([]);
            else
                return json_encode(['url' => $upload->url]);
        }
        $signs = isset($_REQUEST['signs']) ? $_REQUEST['signs'] : null;
        $files = [];
        if(!empty($signs)){
            $uploadPath = \Yii::$app->basePath . \Yii::$app->params['uploadOptions']['uploadPath'];
            foreach(explode(',',$signs) as $_sign){
                $file = UploadedFile::getInstanceByName($_sign);
                if(is_null($file)){
                    $upload = Uploads::findOne($_sign);
                    if(!is_null($upload))
                        $files[] = ['url' => $upload->url, 'duplicate' => true];
                    continue;
                }
                $sign = md5_file($file->tempName);
                $type = $file->type;
                $dir = Uploads::validFileType($type, \Yii::$app->params['uploadOptions']['allowFileTypes']);
                if($dir === false)
                    continue;
                $ext = $file->getExtension();
                $upload = new Uploads();
                $upload->sign = $sign;
                $baseUrl = Uploads::getBaseUrlByDir($dir);
                $upload->path = Uploads::generateDir($uploadPath, $baseUrl);
                $upload->url = \Yii::$app->request->hostInfo . \Yii::$app->request->baseUrl . "/uploads$baseUrl/$sign.$ext";
                $upload->ext = $ext;
                $filename = $upload->path."/$sign.$ext";
                $file->saveAs($filename);
                $upload->save();
                $files[] = ['url' => $upload->url];
            }
        }
        return json_encode($files);
    }

    public function actionJcrop(){
        extract($_POST);
        if(!isset($url))
            return json_encode(['err' => 'url cannot be null', 'data' => []]);
        $src_image = getimagesize($url);
        if(empty($src_image) || !isset($src_image['mime']))
            return json_encode(['err' => 'image initial error', 'data' => []]);
        $mime = $src_image['mime'];
        if(preg_match("/\/(\w+)/i", $mime, $matchs))
            $imgType = $matchs[1];
        else
            return json_encode(['err' => 'wrong image format', 'data' => []]);
        switch($imgType){
            case "jpeg":
                $image = imagecreatefromjpeg($url);
                break;
            case "png":
                $image = imagecreatefrompng($url);
                break;
            case "gif":
                $image = imagecreatefromgif($url);
                break;
            default:
                return json_encode(['err' => 'unsupported image format', 'data' => []]);
        }
        if(!isset($target_format) || !isset($w) || !isset($h))
            return json_encode(['err' => 'target_format must be set', 'data' => []]);
        $dst_w = 0;
        $dst_h = 0;
        $target_format = explode("_", $target_format);
        switch($target_format[0]){
            case "aspect":
                $dst_h = $h;
                $dst_w = $w;
                break;
            case "size":
                $dst_h = $target_format[2];
                $dst_w = $target_format[1];
                break;
            default:
                return json_encode(['err' => 'wrong format type for '.$target_format[0], 'data' => []]);
                break;
        }
        $dst_image = imagecreatetruecolor($dst_w, $dst_h);
        if(!imagecopyresampled($dst_image, $image, 0, 0, $x, $y, $dst_w, $dst_h, $w, $h))
            return json_encode(['err' => 'image create failed', 'data' => []]);
        ob_start();
        imagejpeg($dst_image, null);
        $imageContent = ob_get_contents();
        ob_clean();
        $sign = md5($imageContent);
        $upload = Uploads::findOne($sign);
        if(empty($upload)){
            $uploadPath = \Yii::$app->basePath . \Yii::$app->params['uploadOptions']['uploadPath'];
            $dir = Uploads::validFileType($src_image['mime'], \Yii::$app->params['uploadOptions']['allowFileTypes']);
            $baseUrl = Uploads::getBaseUrlByDir($dir);
            $baseUrl .= "/{$target_format[1]}_{$target_format[2]}";
            $upload = new Uploads();
            $upload->sign = $sign;
            $upload->path = Uploads::generateDir($uploadPath, $baseUrl);
            $upload->url = \Yii::$app->request->hostInfo . \Yii::$app->request->baseUrl . "/uploads$baseUrl/$sign.jpg";
            $upload->ext = "jpg";
            $filename = $upload->path."/$sign.jpg";
            imagejpeg($dst_image, $filename);
            $upload->save();
            return json_encode(['err' => 'ok', 'data' => ['url' => $upload->url]]);
        }else{
            return json_encode(['err' => 'ok', 'data' => ['url' => $upload->url]]);
        }
    }
} 